﻿using AutoMapper;
using B.S.GridManager.Api.Write.Application.Command.LogicGrid;
using B.S.GridManager.ErrorCode;
using B.S.GridManager.Infrastructure.Interface;
using B.S.GridManger.Domain.Entities;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManager.Api.Write.Application.CommandHandler.LogicGrid
{
    /// <summary>
    /// 删除逻辑网格处理类
    /// </summary>
    public class DelLogicGridHandler : IRequestHandler<DelLogicCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogicGridModel> logicRepo;
        private readonly IMapper mapper;

        //private readonly IBaseRepository<DepartmentModel> departRepo;

        /// <summary>
        /// 构造函数注入逻辑网格仓储和mapper
        /// </summary>
        /// <param name="logicRepo">辑网格仓储</param>
        /// <param name="mapper">映射组件对象</param>
        public DelLogicGridHandler(IBaseRepository<LogicGridModel> logicRepo,IMapper mapper)
        {
            this.logicRepo = logicRepo;
            this.mapper = mapper;
            //this.departRepo = departRepo;
        }

        /// <summary>
        /// 删除逻辑网格的终结者处理方法
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns> 
        public Task<ApiResult<int>> Handle(DelLogicCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();//实例化响应包装类

            var entity = logicRepo.GetModel(request.Id);

            if (entity == null) {
                result.Code = ApiEnums.Error;
                result.Msg = "您要删除的逻辑网格不存在";
                result.Data = 0;

                return Task.FromResult(result); //直接返回响应对象
            }

              entity = mapper.Map(request, entity); //把request 转成entity
            entity.IsDeleted = true;

            int r = logicRepo.Update(entity);//调用仓储的Del方法,返回受影响的行数.也就是删除了几行

            if (r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "删除逻辑网格成功!";
                result.Data = r;
            }
            else {
                result.Code = ApiEnums.Fail;
                result.Msg = "删除逻辑网格失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
        }
    }
}
